<script setup lang="ts">
import { useVbenModal, z } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { resetPasswordApi } from '#/api';
import { RegexConstants } from '#/config';

const [CustomLayoutForm, formApi] = useVbenForm({
  wrapperClass: 'grid-cols-1',
  showDefaultActions: false,
  schema: [
    {
      component: 'VbenInputPassword',
      componentProps: {
        placeholder: '请输入原密码',
      },
      fieldName: 'originalPassword',
      label: '原密码',
      rules: 'required',
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        passwordStrength: true,
        placeholder: '请输入新密码',
      },
      fieldName: 'password',
      label: '新密码',
      renderComponentContent() {
        return {
          strengthText: () => RegexConstants.password.description,
        };
      },
      rules: z
        .string()
        .min(6, '密码至少6个字符')
        .max(18, '密码最多18个字符')
        .refine((val) => RegexConstants.password.regex.test(val), {
          message: RegexConstants.password.description,
        }),
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        placeholder: '请输入确认密码',
      },
      fieldName: 'confirmPassword',
      label: '确认密码',
      dependencies: {
        rules(values) {
          const { password } = values;
          return z
            .string({ required_error: $t('authentication.passwordTip') })
            .min(1, { message: $t('authentication.passwordTip') })
            .refine((value) => value === password, {
              message: $t('authentication.confirmPasswordTip'),
            });
        },
        triggerFields: ['password'],
      },
    },
  ],
});

const [Modal, modalApi] = useVbenModal({
  title: '修改密码',
  confirmText: '确认修改',
  onCancel: () => {
    modalApi.close();
  },
  onConfirm: onSubmit,
});

async function onSubmit() {
  const { valid } = await formApi.validate();
  const values = await formApi.getValues();
  if (valid) {
    const msg = await resetPasswordApi(values);
    message.success(msg);
    await modalApi.close();
  }
}
</script>

<template>
  <Modal>
    <CustomLayoutForm />
  </Modal>
</template>
